package com.lixiaoyao.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lixiaoyao.reggie.common.CustomException;
import com.lixiaoyao.reggie.dao.SetmealDao;
import com.lixiaoyao.reggie.entity.Setmeal;
import com.lixiaoyao.reggie.entity.SetmealDish;
import com.lixiaoyao.reggie.entity.SetmealDto;
import com.lixiaoyao.reggie.service.SetmealDishService;
import com.lixiaoyao.reggie.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealDao, Setmeal> implements SetmealService {
    @Autowired
    private SetmealDishService  setmealDishService;

    @Override
    @Transactional
    public void saveWithSetmealDish(SetmealDto setmealDto) {
        //先保存套餐信息
        this.save(setmealDto);

        Long id = setmealDto.getId();

        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        //关系实体列表缺少Setmealid属性，通过stream流为其赋值
        setmealDishes = setmealDishes.stream().map((item)->{
            item.setSetmealId(id);
            return item;
        }).collect(Collectors.toList());
        //再保存套餐菜品关系表
        setmealDishService.saveBatch(setmealDishes);
    }

    @Override
    @Transactional
    public void removeWithSetmealDish(Long setmealId) {
        this.removeById(setmealId);
        LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(setmealId!=null,SetmealDish::getSetmealId,setmealId);
        setmealDishService.remove(queryWrapper);
    }

    @Override
    @Transactional
    public void removeWithSetmealDishs(List<Long> setmealIds) {
        //查询是否可删除(售卖状态)
        //select count(*) from table where id in (1,2,3) and status=0
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(Setmeal::getId,setmealIds);
        queryWrapper.eq(Setmeal::getStatus,1);
        if(this.count(queryWrapper)>0){
            throw new CustomException("套餐售卖中无法删除");
        }
        this.removeByIds(setmealIds);
        //delect * from table where setmealid in (1,2,3)
        LambdaQueryWrapper<SetmealDish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishLambdaQueryWrapper.in(SetmealDish::getSetmealId,setmealIds);
        setmealDishService.remove(dishLambdaQueryWrapper);
    }
}
